package com.originskyseed.platform.task.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.task.mapper.TaskRelateMaintainUserMapper;
import com.originskyseed.platform.task.model.TaskRelateMaintainUser;
import com.originskyseed.platform.task.service.ITaskRelateMaintainUserService;
import com.originskyseed.platform.user.mapper.PlayerMapper;

/**
 * 任务关联维护用户表Service接口实现类（OSI_TASK_RELATE_MAINTAIN_USER）
 *
 * @author wlj
 */
@DubboService
@Component("taskRelateMaintainUserService")
public class TaskRelateMaintainUserServiceImpl implements ITaskRelateMaintainUserService {

	private static final Logger logger = LoggerFactory.getLogger(TaskRelateMaintainUserServiceImpl.class);
	@Resource
	private TaskRelateMaintainUserMapper taskRelateMaintainUserMapper;

	@Resource
	private PlayerMapper playerMapper;


	/**
	 * 删除记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKey(String id) throws Exception {
		return this.taskRelateMaintainUserMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKeys(List<String> ids) throws Exception {
		return this.taskRelateMaintainUserMapper.deleteByPrimaryKeys(ids);
	}

	/**
	 * 插入记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insert(TaskRelateMaintainUser record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.taskRelateMaintainUserMapper.insert(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(TaskRelateMaintainUser record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.taskRelateMaintainUserMapper.insertSelective(record);
	}

	/**
	 * 更新记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKey(TaskRelateMaintainUser record) throws Exception {
		record.setUpdateTime(new Date());
		return this.taskRelateMaintainUserMapper.updateByPrimaryKey(record);
	}

	/**
	 * 根据taskId更新
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateBytaskId(TaskRelateMaintainUser record) throws Exception {
		record.setUpdateTime(new Date());
		return this.taskRelateMaintainUserMapper.updateBytaskId(record);
	}

	/**
	 * 更新记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelective(TaskRelateMaintainUser record) throws Exception {
		record.setUpdateTime(new Date());
		return this.taskRelateMaintainUserMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 更新记录（定时任务）
	 *
	 * @param record
	 * @param tenantCode
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelectiveTenantCode(TaskRelateMaintainUser record, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.updateByPrimaryKeySelective(record);
	}

	/**
	 * 主播在线状态修改
	 *
	 * @param list
	 * @param isOnline
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateAnchorOnlineByList(List<String> list, Integer isOnline) throws Exception {
		return this.taskRelateMaintainUserMapper.updateAnchorOnlineByList(list,isOnline);
	}


	/**
	 * 修改主播的在线状态
	 * @param tenantCode
	 * @param taskRelateMaintainUserList
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateAnchorOnlineByListTenantCode( String tenantCode,List<TaskRelateMaintainUser> taskRelateMaintainUserList) throws Exception
	{
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		List<String> anchorIdList=new ArrayList<>();
		for (TaskRelateMaintainUser relateMaintainUser : taskRelateMaintainUserList) {
			if(relateMaintainUser.getAnchorId()!=null&&StringUtils.isNotBlank(relateMaintainUser.getAnchorId())) {
				anchorIdList.add(relateMaintainUser.getAnchorId());
			}
		}
		TreeMap<String, Object> paramMap = new TreeMap<>();
		paramMap.put("anchorIds",String.join(",",anchorIdList));
		Map resultMap = QueryAppUtil.query("anchorOnlineUrl", 1, paramMap);
		Integer code = Integer.parseInt(resultMap.get("code").toString());
		JSONArray data = new JSONArray();
		if (code == 1) {
			data = JSONArray.parseArray(resultMap.get("data").toString());
		} else {
			logger.error(resultMap.get("msg").toString());
		}
		List<String> updateList = new ArrayList<>();
		if (data != null && data.size() > 0) {
			for (Object ids : data) {
				updateList.add((String) ids);
			}
		}
		if(updateList!=null&&updateList.size()>0) {
			Integer isOnline = 1;
			return taskRelateMaintainUserMapper.updateAnchorOnlineByAnchorIdList(updateList, isOnline);
		}
		return 1;
	}


	/**
	 * 修改主播转换率
	 * @param tenantCode
	 * @param taskRelateMaintainUserList
	 * @return
	 * @throws Exception
	 */
	public int updateAnchorRateByListTenantCode( String tenantCode,List<TaskRelateMaintainUser> taskRelateMaintainUserList) throws Exception
	{
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		List<String> anchorIdList=new ArrayList<>();
		for (TaskRelateMaintainUser relateMaintainUser : taskRelateMaintainUserList) {
			String anchorId=relateMaintainUser.getAnchorId();
			if(anchorId!=null&&StringUtils.isNotBlank(anchorId)) {

				BigDecimal rate = this.playerMapper.selectLiveRateByAnchorId(anchorId);

				BigDecimal percent = rate.setScale(2, BigDecimal.ROUND_HALF_UP);// 取小数点后两位
				relateMaintainUser.setRate(percent);
				this.taskRelateMaintainUserMapper.updateByPrimaryKeySelective(relateMaintainUser);
			}
		}
		return 1;
	}


	@Override
	public int updateAnchorOnlineByListTenantCode(List<String> list, Integer isOnline, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.updateAnchorOnlineByList(list,isOnline);
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public TaskRelateMaintainUser selectByPrimaryKey(String id) throws Exception {
		return this.taskRelateMaintainUserMapper.selectByPrimaryKey(id);
	}

	/**
	 * 根据根据任务ID查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public TaskRelateMaintainUser selectByTaskId(String id) throws Exception {
		return this.taskRelateMaintainUserMapper.selectByTaskId(id);
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<TaskRelateMaintainUser> selectList(TaskRelateMaintainUser record) throws Exception {
		return this.taskRelateMaintainUserMapper.selectList(record);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<TaskRelateMaintainUser> selectListByPage(Map<String, Object> params, BasePage<TaskRelateMaintainUser> page) throws Exception {
		params.put("page", page);
		List<TaskRelateMaintainUser> list = this.taskRelateMaintainUserMapper.selectListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 判断主播是否在线
	 *
	 * @param userType
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<TaskRelateMaintainUser> selectAnchorIsOnlineList(Integer userType, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectAnchorIsOnlineList(userType);
	}

	/**
	 *
	 * @param tenantCode
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<TaskRelateMaintainUser> selectAnchorIsOnlineListListByPage(String tenantCode, HashMap params, BasePage<TaskRelateMaintainUser> page) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		params.put("page", page);
		List<TaskRelateMaintainUser> list = this.taskRelateMaintainUserMapper.selectListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 判断主播是否在线
	 *
	 * @param userType
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<TaskRelateMaintainUser> selectAnchorIsOnlineList(Integer userType) throws Exception {
		return this.taskRelateMaintainUserMapper.selectAnchorIsOnlineList(userType);
	}

}
